<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/11
 * Time: 20:00
 */

namespace app\api\validate;


use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 获取http传入的参数
     * 对这些参数做校验
     */
    public function goCheck()
    {
        $request = Request::instance();
        $params = $request->param();

        $result = $this->batch()->check($params);
        if (!$result) {
            $error = new ParameterException([
                'msg' => $this->error
            ]);
            throw $error;

            /*$error = new ParameterException();
            $error->msg = $this->error;
            throw $error;*/

            /*$error = $this->error;
            throw new Exception($error);*/
        } else {
            return true;
        }
    }

    # 相当于帮 Validate 定义了一个验证规则
    # field 字段
    protected function isPositiveInteger($value, $rule = '',
        $data = '', $field = '')
    {

        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        } else {
            //return $field . '必须是正整数';
            return false;
        }
    }

    protected function isNotEmpty($value, $rule = '',
        $data = '', $field = '')
    {
        if (empty($value)) {
            return false;
        } else {
            return true;
        }
    }

    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|6|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function getDataByRule($arrays)
    {
        // 缓存中获取
        if (array_key_exists('user_id', $arrays) |
            array_key_exists('uid', $arrays))
        {
            // 不允许包含user_id或者uid，防止恶意覆盖user_id
            throw new ParameterException(
                ['msg' => '参数中包含有非法的参数名user_id或id']
            );
        }

        $newArray = [];

        foreach ($this->rule as $key => $value)
        {
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }
}